from django.shortcuts import render, redirect, reverse
from django.views.generic import View
from .forms import RegisterForm, LoginForm, TransferForm
from .models import User
from django.db.models import F
from django.http import HttpResponse
from django.utils.decorators import method_decorator
from .de import login_require



def index(request):
    return render(request, "index.html")


class Signin(View):
    def get(self, request):
        return render(request, "login.html")

    def post(self, request):
        forms = LoginForm(request.POST)
        if forms.is_valid():
            email = forms.cleaned_data.get('email')
            password = forms.cleaned_data.get('password')
            user = User.objects.filter(email=email, password=password).first()
            if user:
                request.session['user_id'] = user.id
                return redirect(reverse('index'))
            else:
                print('用户或密码错误')
                return redirect(reverse('login'))
        else:
            print(forms.errors.get_json_data())
            return redirect(reverse('login'))


class Register(View):
    def get(self, request):
        return render(request, "register.html")

    def post(self, request):
        forms = RegisterForm(request.POST)
        if forms.is_valid():
            username = forms.cleaned_data.get('username')
            password = forms.cleaned_data.get('password')
            email = forms.cleaned_data.get('email')
            User.objects.create(username=username, password=password, email=email, balance=1000)
            return redirect(reverse('login'))
        else:
            print(forms.errors.get_json_data())
            return redirect(reverse('register'))


@method_decorator(login_require, name='dispatch')
class Transfer(View):
    def get(self, request):
        return render(request, "transfer.html")

    def post(self, request):
        forms = TransferForm(request.POST)
        if forms.is_valid():
            email = forms.cleaned_data.get('email')
            money = forms.cleaned_data.get('money')
            user_id = request.session.get('user_id')
            user = User.objects.get(pk=user_id)
            if user.balance >= money:
                user.balance = user.balance - money
                User.objects.filter(email=email).update(balance=F('balance') + money)
                user.save()
                return HttpResponse("转账成功")
            else:
                return HttpResponse("余额不足")
        else:
            print(forms.errors)
            return redirect(reverse("transfer"))


